package code.google.model.util;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import code.google.model.groove.GrooveClient;
import code.google.model.local.LocalClient;
import code.google.model.player.StreamingPlayer;
import code.google.model.util.interfaces.IGrooveClientCreationCallback;

public class ModelProvider {
	
	private static ModelProvider instance;
	
	private List<IGrooveClientCreationCallback> grooveCallbacks;
	
	private GrooveClientCreationTask task;
	
	private GrooveClient grooveClient;
	private LocalClient localClient;

	private StreamingPlayer streamingPlayer;
	
	private ModelProvider(){
		grooveCallbacks = new ArrayList<IGrooveClientCreationCallback>();
		localClient = new LocalClient();
		streamingPlayer = new StreamingPlayer();
	}
	
	public static ModelProvider getInstance(){
		if(instance == null)
			instance = new ModelProvider();
		return instance;
	}
	
	
	public void getGrooveClient(IGrooveClientCreationCallback callback){
		if(grooveClient != null)
			callback.onClientCreationComplete(grooveClient);
		else{
			grooveCallbacks.add(callback);
			if(task == null){
				task = new GrooveClientCreationTask();
				task.execute();
			}
		}
	}
	
	public LocalClient getLocalClient() {
		return localClient;
	}
	
	public StreamingPlayer getStreamingPlayer(){
		return streamingPlayer;
	}

	private class GrooveClientCreationTask extends
			AsyncTask<Void, Void, GrooveClient> {

		@Override
		protected GrooveClient doInBackground(Void... params) {
			grooveClient = new GrooveClient();
			return grooveClient;
		}

		@Override
		protected void onPostExecute(GrooveClient result) {
			for (IGrooveClientCreationCallback callback : grooveCallbacks) {
				callback.onClientCreationComplete(result);
			}
			grooveCallbacks.clear();
		}
	}
	
}
